package org.microframework.cloud.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.microframework.cloud.gateway.exception.RouteNotFoundException;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

/**
 * 路由验证过滤器
 * 检查请求是否匹配到有效路由，如果没有匹配到则抛出RouteNotFoundException
 */
@Slf4j
@Component
public class RouteValidationFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 检查是否匹配到路由
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        if (route == null) {
            String path = exchange.getRequest().getURI().getPath();
            log.warn("未找到路由: {}", path);
            return Mono.error(new RouteNotFoundException(path));
        }
        
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 在大多数过滤器之后执行，但在异常处理之前
        return Ordered.LOWEST_PRECEDENCE - 10;
    }
} 